<?php

namespace App\Admin\Grid;

use App\Admin\Grid;
use App\Admin\Grid\Exporters\CsvExporter;

class Exporter
{
    /**
     * @var Grid
     */
    protected $grid;

    /**
     * 所有可用的导出驱动
     *
     * @var array
     */
    protected static $drivers = [];

    /**
     * 请求中表示有导出的查询字段名
     *
     * @var string
     */
    public static $queryName = '_export_';

    /**
     * 导出所有记录的标志
     */
    const SCOPE_ALL = 'all';

    /**
     * 导出本页记录的标志
     */
    const SCOPE_CURRENT_PAGE = 'page';

    /**
     * 导出所选记录的标志
     */
    const SCOPE_SELECTED_ROWS = 'selected';

    /**
     * Create a new Exporter instance.
     *
     * @param Grid $grid
     */
    public function __construct(Grid $grid)
    {
        $this->grid = $grid;
    }

    /**
     * 设置其他的请求导出查询字段名
     *
     * @param $name
     */
    public static function setQueryName($name)
    {
        static::$queryName = $name;
    }

    /**
     * 添加一个导出驱动
     *
     * @param $driver
     * @param $extend
     */
    public static function extend($driver, $extend)
    {
        static::$drivers[$driver] = $extend;
    }

    /**
     * 为导出器设置表格实例
     *
     * @param $driver
     * @return Grid\Exporters\AbstractExporter|CsvExporter
     */
    public function resolve($driver)
    {
        if ($driver instanceof Grid\Exporters\AbstractExporter) {
            return $driver->setGrid($this->grid);
        }

        return $this->getExporter($driver);
    }

    /**
     * 获取导出器实例,并设置表格实例
     *
     * @param string $driver
     *
     * @return CsvExporter|Grid\Exporters\AbstractExporter
     */
    protected function getExporter($driver)
    {
        if (!array_key_exists($driver, static::$drivers)) {
            return $this->getDefaultExporter();
        }

        return new static::$drivers[$driver]($this->grid);
    }

    /**
     * 获取默认的导出器(导出为.csv文件)
     *
     * @return CsvExporter
     */
    public function getDefaultExporter()
    {
        return new CsvExporter($this->grid);
    }

    /**
     * 返回不同类型导出的url查询字段键值
     *
     * @param string $scope
     * @param mixed  $args
     * @return array
     */
    public static function formatExportQuery($scope = '', $args = null)
    {
        $query = '';
        if ($scope == static::SCOPE_ALL) {
            $query = 'all';
        }
        if ($scope == static::SCOPE_CURRENT_PAGE) {
            $query = "page";
        }
        if ($scope == static::SCOPE_SELECTED_ROWS) {
            $query = "selected:$args";
        }

        return [static::$queryName => $query];
    }
}
